#coding:utf8
from rest_framework import serializers
from .models import User
import re
from django_redis import get_redis_connection
from django.conf import settings

# serializers.ModelSerializer
# serializers.Serializer

# 数据要入库, ModelSerializer create/update 方法
class RegisterCreateUserSerialzier(serializers.ModelSerializer):
    """
    1.获取前段提交的数据, username,password,password2,mobile,sms_code,allow
    2.对提交的数据进行校验
        # # 多个字段验证
        # 2.1 密码是否一致
        # 2.2 短信验证码
        #
        # #单个字段验证
        # 2.3 手机号是否正确
        # 2.4 allow校验
    3.保存入库
    """

    # ModelSerializer 是根据 fields 自动生成字段,
    # 但是我的 fields 列表中 只有 三个字段

    # 手动写上
    # required 必须的  既能实现 序列化 还能实现反序列化
    # write_only 只能写入,而且在反序列化的时候 必须写入
    password2 = serializers.CharField(label='确认密码',write_only=True,
                                      allow_null=False,allow_blank=False)
    sms_code = serializers.CharField(label='短信验证码',write_only=True,
                                     max_length=6,min_length=6)
    allow = serializers.CharField(label='是否同意协议',write_only=True,
                                  allow_null=False,allow_blank=False)

    token = serializers.CharField(label='进行序列化操作返回的token',read_only=True)

    class Meta:

        model = User
        # 手动实现的3个字段,需要添加到fields中
        fields = ['id','username','password','mobile','password2','sms_code','allow','token']

        extra_kwargs = {
            'id':{'read_only':True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # #单个字段验证
    # 2.3 手机号是否正确
    def validate_mobile(self,value):

        if not re.match(r'1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机号不符合规则')

        return value

    # 2.4 allow校验
    def validate_allow(self,value):

        if value != 'true':
            raise serializers.ValidationError('请同意协议')

        return True

    # # 多个字段验证
    # 2.1 密码是否一致
    # 2.2 短信验证码
    def validate(self, attrs):

        # 2.1 密码是否一致
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError('密码不一致')
        # 2.2 短信验证码
        sms_code = attrs.get('sms_code')
        mobile = attrs['mobile']
        # I, 连接redis
        redis_conn = get_redis_connection('code')
        # II 获取 redis的短信验证码
        redis_code = redis_conn.get('sms_%s'%mobile)
        if redis_code is None:
            raise serializers.ValidationError('短信验证码过期')
        # III 比较
        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码不一致')


        return attrs


    def create(self, validated_data):



        # print(validated_data)
        # validated_data 多三个字段
        #BookInfo.objects.create(**validated_data)

        # 删除多余字段
        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']

        # validated_data 删除多余的字段之后就满足需求了,所以我们这个时候就可以入库

        # User.objects.create(**validated_data)

        user = super().create(validated_data)


        # 密码需要加密
        user.set_password(validated_data['password'])
        user.save()


        # 需要在创建了用户之后,我们采用 jwt给它生成一个token
        from rest_framework_jwt.settings import api_settings

        # 获取2个方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 调用这2个方法
        # 把用户的信息给 payload
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)


        # 把token信息 传递给user
        # 让我们在进行 序列化操作的时候把token返回给浏览器
        user.token = token

        # 一定要保存
        return user



class UserCenterInfoSerializer(serializers.ModelSerializer):


    class Meta:
        model = User
        fields = ['id','username','mobile','email','email_active']

class EmailUpdateSerializer(serializers.ModelSerializer):

    class Meta:

        model = User
        fields = ['id','email']

        extra_kwargs = {
            'email': {
                'required': True
            }
        }


    #序列化器中进行更新操作
    # 只是更新邮件信息
    def update(self, instance, validated_data):

        email = validated_data.get('email')
        instance.email = email
        instance.save()

        # 我们在这里发送邮件
        from django.core.mail import send_mail

        #subject, message, from_email, recipient_list,html_message=None
        #subject: 主题
        subject = '美多商城激活邮件'
        # message,  内容,普通内容
        message = ''
        # from_email,  谁发送的
        from_email = settings.EMAIL_FROM
        # recipient_list: 谁接收 []
        recipient_list = [email]
        # html_message  , 丰富的邮件内容可以传递 html
        # html_message = '<h1>lalala</h1>'

        # 生成一个 对id和email进行处理的一个url
        verify_url = instance.generice_active_url()

        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)


        # send_mail(subject,
        #           message,
        #           from_email,
        #           recipient_list,
        #           html_message=html_message)

        from celery_tasks.email.tasks import send_verify_email

        send_verify_email.delay(subject,
                  message,
                  from_email,
                  recipient_list,
                  html_message=html_message)

        return instance

from goods.models import SKU
class UserHistorySerializer(serializers.Serializer):

    sku_id = serializers.CharField(label='商品id',required=True)


    # def validate(self, attrs):


    def validate_sku_id(self,value):

        #判断商品是否存在
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    # 因为我们在视图中,调用了save方法, save方法我们需要重写,让
    #数据保存在 Redis
    def create(self, validated_data):

        # 我们记录用户记录的时候, key 确保用户记录的唯一性
        # history_id
        # history_1
        user = self.context['request'].user
        sku_id = validated_data.get('sku_id')

        #1. 连接redis
        redis_conn = get_redis_connection('history')
        #2. 保存在列表中,先把重复的删除
        redis_conn.lrem('history_%s'%user.id,0,sku_id)
        #3. 再添加数据
        redis_conn.lpush('history_%s'%user.id,sku_id)
        # 4.只保留5条记录就可以(Redis保留不能太多的数据)
        redis_conn.ltrim('history_%s'%user.id,0,4)


        return validated_data


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')
from users.models import Address
class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):
        #Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)